﻿#include "stu_sign_in.h"
#include "ui_stu_sign_in.h"
#include<QDateTime>
#include<QTimer>
#include<QSqlQuery>
#include<QMessageBox>
#include"maininterface.h"
Stu_sign_in::Stu_sign_in(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Stu_sign_in)
{
    ui->setupUi(this);
    num=0;//识别次数初始化
    timer_3.start(1000);
    connect(&timer_3,&QTimer::timeout ,this,&Stu_sign_in::showtime);
    connect(&timer_4,&QTimer::timeout ,this,&Stu_sign_in::readframe);
    //加载opencv分类器
   cascade.load("G:\\haarcascade_frontalface_alt2.xml");
   model = face::FisherFaceRecognizer::create();
  //1.加载训练好的模型
   model->read("E:\\MyFaceFisherModel.xml");





   QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
   //设置数据库名，指明路径
   db.setDatabaseName("G:\\Admin.db");
   if(!db.open())
   {
       qDebug()<<"open error";
      //cout<<"open false"<<endl;
   }


}

Stu_sign_in::~Stu_sign_in()
{
    delete ui;
}
//显示当前时间
void Stu_sign_in::showtime()
{
   QDateTime current_time=QDateTime::currentDateTime();

    ui->label_timeshow->setText(current_time.toString("yyyy-MM-dd"));
    ui->label_timeshow_2->setText(current_time.toString("hh:mm"));
}
//打开摄像头，开始签到
void Stu_sign_in::on_pushButton_clicked()
{
   capture.open(0,cv::CAP_DSHOW);
   timer_4.start(20);
}
//从模型中返回人脸标签
int Stu_sign_in::Predict(Mat &image)
{
    Mat face_test;
    int predict = 0;
    //截取的ROI人脸尺寸调整
    if (image.rows >= 120)
    {
        //改变图像大小，使用双线性差值
      cv::resize(image, face_test, Size(92, 112));

    }
    //判断是否正确检测ROI
    if (!face_test.empty())
    {
        //测试图像应该是灰度图
        predict = model->predict(face_test);
    }

    return predict;
}

//读取摄像头信息，识别人脸,进行打卡
void Stu_sign_in::readframe()
{
    //在标签中显示人脸
    capture>>frame;
    std::vector<Rect>faces(0);
    cvtColor(frame,gray,COLOR_BGR2GRAY);
     equalizeHist(gray, gray); //变换后的图像进行直方图均值化处理
    cascade.detectMultiScale(gray, faces,1.1, 4, CASCADE_DO_ROUGH_SEARCH, Size(30, 30), Size(500, 500));
    for(int i=0;i<faces.size();i++)
    {
        rectangle(frame,faces[i],Scalar(0,0,255),2,8,0 );
    }
        cvtColor(frame,frameRGB,COLOR_BGR2RGB);
        QImage image(frameRGB.data, frameRGB.cols, frameRGB.rows, frameRGB.step1() , QImage::Format_RGB888);//存入格式为R, G, B 对应 0,1,2
        QPixmap pixmap = QPixmap::fromImage(image);//利用 QImage（独立硬件，存储客户端） 的数据填充 QPixmap(依赖于硬件),来显示图像，可以加速显示
        ui->label_faceshow->setScaledContents(true);//图像缩放，自适应Label大小
        ui->label_faceshow->setPixmap(pixmap);
    //
    if(faces.size()==1)
    {
        time=QDateTime::currentDateTime().toString("MM-dd hh:mm");
        Mat ROIface=gray(faces[0]);

        //qDebug()<<"detect"<<detect<<"predict"<<Predict(ROIface);
     if(detect==Predict(ROIface))
     {
         num++;

        if(num==3)
      {
        QString sql_Attend = QString("select * from Attenddence  where Sno='%1'").arg(Predict(ROIface));
        QSqlQuery query_Attend(sql_Attend);
        while(query_Attend.next())
          {
            QString message = query_Attend.value(3).toString()+QString::fromLocal8Bit(",您已打卡");
            QMessageBox::about(this, QString::fromLocal8Bit("提示"),message);
            i++;
            qDebug()<<"i="<<i;
            return;
          }
        QString sql_stu=QString("select * from Student where Number='%1'").arg(Predict(ROIface));
        QSqlQuery query_stu(sql_stu);
        while(query_stu.next())
          {
            j++;
            QString message_1 = query_stu.value(2).toString()+QString::fromLocal8Bit(",打卡成功！");
            QMessageBox::about(this, QString::fromLocal8Bit("提示"),message_1);
            ui->lineEdit->setText(query_stu.value(1).toString());
            ui->lineEdit_2->setText(query_stu.value(2).toString());
            ui->lineEdit_3->setText(query_stu.value(3).toString());
            ui->lineEdit_4->setText(query_stu.value(4).toString());

            QString str_add=QString("insert into Attenddence(Sno,Time,level) values('%1','%2','%3')")
             .arg(query_stu.value(1).toString()).arg(time).arg(query_stu.value(2).toString());
           QSqlQuery query_add(str_add);
            qDebug()<<"j="<<j;
           if(!query_add.exec())
           {

            qDebug()<<"add error";
          }
           else
           {
               qDebug()<<"add success ";
           }
        }
        }
     }
     else
     {
         num=0;
     }
     detect=Predict(ROIface);
 }
}

//关闭摄像头
void Stu_sign_in::on_pushButton_2_clicked()
{
    timer_4.stop();
    capture.release();
}

//返回上级界面
void Stu_sign_in::on_pBback_stu_clicked()
{
    MainInterface *w=new MainInterface();
    w->show();
    this->close();
}
